"""
邮件发送工具
基于系统SMTP配置发送邮件通知
"""
import smtplib
import logging
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from typing import Optional, List
from motor.motor_asyncio import AsyncIOMotorDatabase
from bson import ObjectId
from app.models.settings import SystemSettingsModel, SMTPEncryption

logger = logging.getLogger(__name__)


class EmailSender:
    """邮件发送器"""
    
    @staticmethod
    async def get_smtp_config(db: AsyncIOMotorDatabase) -> Optional[dict]:
        """获取SMTP配置"""
        try:
            settings_doc = await db.system_settings.find_one()
            if not settings_doc:
                return None
            
            # 这里需要根据实际的SystemSettingsModel结构来解析
            # 假设settings_doc中有notification字段
            notification_settings = settings_doc.get("notification", {})
            
            if not notification_settings.get("email_enabled", False):
                return None
            
            return {
                "host": notification_settings.get("smtp_host", ""),
                "port": notification_settings.get("smtp_port", 587),
                "username": notification_settings.get("smtp_username", ""),
                "password": notification_settings.get("smtp_password", ""),
                "encryption": notification_settings.get("smtp_encryption", SMTPEncryption.TLS),
                "enabled": notification_settings.get("email_enabled", False)
            }
        except Exception as e:
            logger.error(f"获取SMTP配置失败: {str(e)}")
            return None
    
    @staticmethod
    async def send_email(
        db: AsyncIOMotorDatabase,
        to_email: str,
        subject: str,
        content: str,
        html_content: Optional[str] = None
    ) -> bool:
        """
        发送邮件
        
        Args:
            db: 数据库连接
            to_email: 收件人邮箱
            subject: 邮件主题
            content: 纯文本内容
            html_content: HTML内容（可选）
        
        Returns:
            bool: 是否发送成功
        """
        try:
            # 获取SMTP配置
            smtp_config = await EmailSender.get_smtp_config(db)
            if not smtp_config or not smtp_config.get("enabled"):
                logger.warning("邮件功能未启用或SMTP配置不存在")
                return False
            
            # 创建邮件消息
            msg = MIMEMultipart('alternative')
            msg['Subject'] = subject
            msg['From'] = smtp_config["username"]
            msg['To'] = to_email
            
            # 添加纯文本内容
            text_part = MIMEText(content, 'plain', 'utf-8')
            msg.attach(text_part)
            
            # 添加HTML内容（如果有）
            if html_content:
                html_part = MIMEText(html_content, 'html', 'utf-8')
                msg.attach(html_part)
            
            # 连接SMTP服务器并发送
            encryption = smtp_config.get("encryption", SMTPEncryption.TLS)
            
            if encryption == SMTPEncryption.TLS:
                server = smtplib.SMTP(smtp_config["host"], smtp_config["port"])
                server.starttls()
            elif encryption == SMTPEncryption.SSL:
                server = smtplib.SMTP_SSL(smtp_config["host"], smtp_config["port"])
            else:
                server = smtplib.SMTP(smtp_config["host"], smtp_config["port"])
            
            # 登录
            server.login(smtp_config["username"], smtp_config["password"])
            
            # 发送邮件
            server.send_message(msg)
            server.quit()
            
            logger.info(f"邮件发送成功: {to_email} - {subject}")
            return True
            
        except Exception as e:
            logger.error(f"发送邮件失败: {str(e)}")
            return False
    
    @staticmethod
    async def send_notification_email(
        db: AsyncIOMotorDatabase,
        to_email: str,
        notification_type: str,
        title: str,
        content: str,
        related_url: Optional[str] = None
    ) -> bool:
        """
        发送通知邮件
        
        Args:
            db: 数据库连接
            to_email: 收件人邮箱
            notification_type: 通知类型
            title: 通知标题
            content: 通知内容
            related_url: 相关链接（可选）
        
        Returns:
            bool: 是否发送成功
        """
        # 生成HTML邮件内容
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
                .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
                .header {{ background-color: #409EFF; color: white; padding: 20px; text-align: center; }}
                .content {{ padding: 20px; background-color: #f9f9f9; }}
                .button {{ display: inline-block; padding: 10px 20px; background-color: #409EFF; color: white; text-decoration: none; border-radius: 4px; margin-top: 20px; }}
                .footer {{ text-align: center; padding: 20px; color: #999; font-size: 12px; }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h2>{title}</h2>
                </div>
                <div class="content">
                    <p>{content}</p>
                    {f'<a href="{related_url}" class="button">查看详情</a>' if related_url else ''}
                </div>
                <div class="footer">
                    <p>此邮件由系统自动发送，请勿回复。</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        return await EmailSender.send_email(
            db=db,
            to_email=to_email,
            subject=title,
            content=content,
            html_content=html_content
        )

